/*
 * @Author: frp
 * @Date: 2020-10-06 19:32:05
 * @LastEditTime: 2020-10-08 14:29:21
 * @LastEditors: YoungWind
 * @Description: In User Settings Edit
 * @FilePath: \ccd3\src\ccd3\line\charts\LineChart.js
 */
import BaseChart from '../../BaseChart.js'

export default class LineChart extends BaseChart {
	constructor(id, data) {
		super(id, data)

		this.xAxisKey = ''
		this.yAxisKey = ''

		this.xAxis = null
		this.xAxisGroup = null

		this.yAxis = null
		this.yAxisGroup = null

		this.lineGroup = null

		this.lineWidth = 1
		this.color = 'red'
	}

	/**
	 * @description: 设置x轴数据的字段名
	 * @param {x轴的key}
	 * @return {当前对象}
	 */
	setXAxisKey(k) {
		this.xAxisKey = k
		return this
	}
	/**
	 * @description: 设置y轴数据的字段名
	 * @param {y轴的key}
	 * @return {当前对象}
	 */
	setYAxisKey(k) {
		this.yAxisKey = k
		return this
	}

	setColor(c) {
		this.color = c
		return this
	}

	setLineWidth(w) {
		this.lineWidth = w
		return this
	}

	init() {
		this.initSvg()
		this.initMainGroup()

		this.initLineGroup() //初始化存放line（也就是path路径）的容器，如果是面向过程编程就应该现有比例尺才能有折线，但面向对象编程是对折线进行抽象，假设他已经存在了
		this.initAxesGroup()
		return this
	}

	initLineGroup() {
		this.lineGroup = this.mg.append('g')
	}

	initAxesGroup() {
		this.xAxisGroup = this.svg
			.append('g')
			.attr('id', `${this.id}xAxis`)
			.attr('transform', `translate(${this.margin.left},${this.margin.top + this.innerHeight})`)

		this.yAxisGroup = this.svg
			.append('g')
			.attr('id', `${this.id}yAxis`)
			.attr('transform', `translate(${this.margin.left},${this.margin.top})`)
	}

	render(data) {
		if (data) {
			this.data = data
		}
		this.renderScale()
		this.renderAxes()
		this.renderLine()
		return this
	}

	renderScale() {
		this.xAxisScale = d3
			.scalePoint()
			.domain(this.data.map((d) => d[this.xAxisKey]))
			.range([0, this.innerWidth])

		this.yAxisScale = d3
			.scaleLinear()
			.domain([0, d3.max(this.data, (d) => +d[this.yAxisKey])])
			.nice()
			.range([this.innerHeight, 0])
	}

	renderLine() {
		this.lineGroup
			.selectAll('path')
			.data([this.data])
			.join('path')
			.transition()
			.style('fill', 'none')
			.style('stroke', this.color)
			.style('stroke-width', this.lineWidth)
			.attr(
				'd',
				d3
					.line()
					.x((d) => this.xAxisScale(d[this.xAxisKey]))
					.y((d) => this.yAxisScale(d[this.yAxisKey]))
			)
	}
	/**
	 * @description: 更新坐标轴
	 * @param {type}
	 * @return {type}
	 */
	renderAxes() {
		this.xAxisGroup.transition().call(d3.axisBottom(this.xAxisScale))

		this.yAxisGroup.transition().call(d3.axisLeft(this.yAxisScale))
	}
}
